//
//  MarkView.m
//  StencilProject
//
//  Created by 镭驰技术开发-2 on 16/8/11.
//  Copyright © 2016年 张鹏君. All rights reserved.
//

#import "StarView.h"
#define FOREGROUND_STAR_IMAGE_NAME @"btn_big_xing.1"
#define BACKGROUND_STAR_IMAGE_NAME @"btn_big_xing.2"

@interface StarView ()

@property (nonatomic, strong) UIView *foregroundStarView;
@property (nonatomic, strong) UIView *backgroundStarView;
@property (nonatomic, assign) NSInteger numberOfStars;
@property (nonatomic, assign) CGFloat mark;//得分值
@end

@implementation StarView
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        [self setDataAndUI];
    }
    return self;
    
}
#pragma mark - Private Methods
- (void)setDataAndUI {
    _numberOfStars = 5;
    self.foregroundStarView = [self createStarViewWithImage:FOREGROUND_STAR_IMAGE_NAME ];
    self.backgroundStarView = [self createStarViewWithImage:BACKGROUND_STAR_IMAGE_NAME];
    
    [self addSubview:self.backgroundStarView];
//    [self addSubview:self.foregroundStarView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userTapRateView:)];
    tapGesture.numberOfTapsRequired = 1;
    [self addGestureRecognizer:tapGesture];
}

- (void)userTapRateView:(UITapGestureRecognizer *)gesture {
    [self addSubview:self.foregroundStarView];
    CGPoint tapPoint = [gesture locationInView:self];
    CGFloat offset = tapPoint.x;
    CGFloat realStarScore = offset / (self.bounds.size.width / self.numberOfStars);
    _mark = ceil(realStarScore);
    self.foregroundStarView.frame = CGRectMake(0, 0, self.bounds.size.width * (_mark/5), self.bounds.size.height);
    if ([self.delegate respondsToSelector:@selector(getMark:)]) {
        [self.delegate getMark:_mark];
    }
}

- (UIView *)createStarViewWithImage:(NSString *)imageName {
    UIView *view = [[UIView alloc] initWithFrame:self.bounds];
    view.clipsToBounds = YES;
    view.backgroundColor = [UIColor clearColor];
    for (NSInteger i = 0; i < self.numberOfStars; i ++)
    {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
        NSLog(@"%f",self.bounds.size.width / self.numberOfStars);
        imageView.frame = CGRectMake(i * self.bounds.size.width / self.numberOfStars, 0, self.bounds.size.width / self.numberOfStars, self.bounds.size.height);
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [view addSubview:imageView];
    }
    return view;
}
- (void)showMarkWithStar:(CGFloat)mark{
    NSLog(@"%f",mark);
    [self addSubview:self.foregroundStarView];
    self.foregroundStarView.frame = CGRectMake(0, 0, self.bounds.size.width * (mark/5), self.bounds.size.height);
}
@end
